package com.zqc.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * IP注册接口的防爆刷控制
 * 超过阈值，直接返回错误码与错误信息：303，您频繁进行注册，请求已被拒绝 *
 */
@Slf4j
@Component
@Order(1)
public class IpFilter implements GlobalFilter {
    // 存储每个IP请求的访问量
    // key - IP  value - 访问时间
    private volatile static Map<String, CopyOnWriteArrayList<Long>> ipMap = new ConcurrentHashMap<>();

    // 最大请求数
    @Value("${ip.maxreqnum}")
    private Integer ipMaxReqNum;

    // 多少分钟内
    @Value("${ip.minute}")
    private Integer ipMinute;

    /**
     * 爆刷分析：
     * 1. 记录每个IP请求时间
     * 2. 统计从当前时间开始，前推ipMinute分钟，统计出共请求多少次
     * 3. 如果达到ipMaxReqNum限制，则报错
     * 4. 每次同IP请求时，将过期的时间请求记录清除，以释放空间
     */

    private final static String REQUEST_TIME_BEGIN = "requestTimeBegin";

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("   IpFilter...");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getPath().toString();
        if (path.startsWith("/api/code/create")) {
            String ip = request.getRemoteAddress().getAddress().getHostAddress();
            ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
            if (!ipMap.containsKey(ip)) {
                CopyOnWriteArrayList<Long> list = new CopyOnWriteArrayList<>();
                list.add(System.currentTimeMillis());
                ipMap.put(ip, list);
            } else {
                CopyOnWriteArrayList<Long> list = ipMap.get(ip);
                Iterator<Long> iterator = list.iterator();
                int requestCount = 0;
                Long now = System.currentTimeMillis();
                while (iterator.hasNext()) {
                    Long requstTime = iterator.next();
                    if (now - requstTime > ipMinute * 60 * 1000) {
                        list.remove(requstTime);
                    } else {
                        requestCount++;
                    }
                }
                log.info(ip + ", " + ipMinute + "分钟内，请求次数共" + requestCount + "，阈值=" + ipMaxReqNum);
                if (requestCount > ipMaxReqNum) {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    log.info("=====>IP：" + ip + " 爆刷");
                    String data = "错误码：303，错误信息：您频繁进行注册，请求已被拒绝！";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes("UTF-8"));
                    return response.writeWith(Mono.justOrEmpty(wrap));
                } else {
                    ipMap.get(ip).add(System.currentTimeMillis());
                }
            }
        }

        return chain.filter(exchange);
    }
}
